package marchsoft.modules.system.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.system.entity.DictTYpe;
import marchsoft.modules.system.entity.Job;
import marchsoft.modules.system.service.IDictService;
import marchsoft.response.Result;
import marchsoft.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dict_type")
@Api(tags = "系统：字典管理")
public class DictTypeController {

    private static final String ENTITY_NAME = "dict_type";

    private final IDictService dictService;

    @ApiOperation("查询字典主表")
    @GetMapping
    @PreAuthorize("@smpe.check('dict_type:list')")
    public Result<Object> query(String typeName,
                                @RequestParam(value ="pageNum",defaultValue = "1")Long pageNum,
                                @RequestParam(value ="pageSize",defaultValue = "10") Long pageSize) {
        return dictService.findByAllDictType(typeName,new Page(pageNum,pageSize));
    }


    @ApiOperation("修改字典主表")
    @PutMapping
    @PreAuthorize("@smpe.check('dict_type:edit')")
    public Result<Object> update(@RequestBody DictTYpe dictTYpe) {
        log.info(StrUtil.format("【修改字典主表 /api/dict_type】操作人id：{}，被修改字典主表id：{}", SecurityUtils.getCurrentUserId(), dictTYpe.getId()));
        return dictService.updateDictType(dictTYpe);
    }

    @ApiOperation("删除字典主表")
    @DeleteMapping
    @PreAuthorize("@smpe.check('dict_type:del')")
    public Result<Object> delete(@RequestBody Set<Long> ids) {
        log.info(StrUtil.format("【删除字典主表 /api/dict_type】操作人id：{}，被删除字典主表id：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
        return dictService.deleteDictType(ids);
    }

    @ApiOperation("新增字典主表")
    @PostMapping
    @PreAuthorize("@smpe.check('dict_type:add')")
    public Result<Object> create(@RequestBody DictTYpe dictTYpe) {
        log.info(StrUtil.format("【新增字典主表 /api/dict_type】操作人id：{}，字典主表名称：{}", SecurityUtils.getCurrentUserId(), dictTYpe.getDictTypeName()));
        if (ObjectUtil.isNotNull(dictTYpe.getId())) {
            log.error(StrUtil.format("【新增字典主表失败】操作人id：{}，新增字典主表实体默认id应该为空，Job：{}", SecurityUtils.getCurrentUserId(), dictTYpe));
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        return dictService.createDictType(dictTYpe);
    }
}
